package com.jeffgalper.feather;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

public class FeatherableFile extends AbstractFeatherable {

  private File mFile;

  public FeatherableFile(String filename) throws FileNotFoundException {
    this(new File(filename));
  }

  public FeatherableFile(File file) throws FileNotFoundException {
    mFile = file;
  }

  public String getUPath() {
    return mFile.getPath() + (mFile.isDirectory() ? "/" : "");
  }

  public boolean isDirectory() {
    return mFile.isDirectory();
  }

  public long getFileSize() throws FeatherException {
    if (isDirectory())
      throw new FeatherException("Directories have no size");
    return mFile.length();
  }

  public void write(FileChannel fc) throws IOException, FeatherException {
    FileInputStream in = null;
    FileChannel fcIn = null;
    try {
      in = new FileInputStream(mFile);
      fcIn = in.getChannel();
      int bytesTransferred = 0;
      long size = getFileSize();
      while (bytesTransferred < size) {
        bytesTransferred += fcIn.transferTo(bytesTransferred, size
            - bytesTransferred, fc);
      }
    } finally {
      if (fcIn != null)
        fcIn.close();
      if (in != null)
        in.close();
    }

  }

  public List<Featherable> getChildren() throws FeatherException {
    List<Featherable> files = new ArrayList<Featherable>();
    try {
      for (File file : mFile.listFiles()) {
        files.add(new FeatherableFile(file));
      }
    } catch (FileNotFoundException e) {
      throw new FeatherException(e);
    }
    return files;
  }

}
